package com.epam.training.service.insurance;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.epam.training.domain.Insurance;
import com.epam.training.repository.InsuranceRepository;

@Service
public class InsuranceServiceImpl implements InsuranceService {
	private static final int PAGE_SIZE = 10;

	@Autowired
	private InsuranceRepository repository;

	@Override
	public List<Insurance> getAllInsurance() {
		return repository.findAll();
	}

	@Override
	public Page<Insurance> getAllInsurance(Integer pageNumber) {
		PageRequest pageRequest = new PageRequest(pageNumber - 1, PAGE_SIZE);
		return repository.findAll(pageRequest);
	}

	@Transactional
	@Override
	public void save(Insurance insurance) {
		repository.save(insurance);
	}

	@Override
	public Insurance getById(Integer id) {
		return repository.findOne(id);
	}

	@Override
	public void delete(Integer id) {
		repository.delete(id);
	}

	@Override
	public void update(Insurance insurance, Integer id) {
		Insurance insuranceDB = repository.findOne(id);

		insuranceDB.setName(insurance.getName());
		insuranceDB.setPrice(insurance.getPrice());
		insuranceDB.setDescription(insurance.getDescription());

		repository.save(insuranceDB);
	}

}
